﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using UnityEngine;

public class FilePointDownLoad {
    public float Progress { get; private set; }
    private bool isStop;
    private Thread _thread = null;
    public bool IsDone { get; private set; }

    public void DownLoad(string url, string savepath, Action callback)
    {
        IsDone = false;
        isStop = false;
        _thread = new Thread(() =>
        {
            string saveDir = savepath.Substring(0, savepath.LastIndexOf('/'));
            if (!Directory.Exists(saveDir))
            {
                Directory.CreateDirectory(saveDir);
            }
            string filePath = savepath;
            FileStream fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            long fileLength = fileStream.Length;
            long totalFileLength = GetFileSize(url);
            if (fileLength < totalFileLength)
            {
                fileStream.Seek(fileLength, SeekOrigin.Begin);
                HttpWebRequest  httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
                httpWebRequest.AddRange((int)fileLength);
                Stream stream = httpWebRequest.GetRequestStream();
                byte[] buffer = new byte[1024];
                int length = stream.Read(buffer, 0, buffer.Length);
                while (length > 0)
                {
                    if (isStop) break;
                    fileStream.Write(buffer, 0, buffer.Length);
                    fileLength += length;
                    Progress = (float) fileLength / totalFileLength;
                    length = stream.Read(buffer, 0, buffer.Length);
                }
                stream.Close();
                stream.Dispose();
            }
            else
            {
                Progress = 1;
            }
            fileStream.Close();
            fileStream.Dispose();
            if (Progress >= 1)
            {
                if (callback != null)
                {
                    callback();
                }
            }
        });
        _thread.IsBackground = true;
        _thread.Start();
    }

    private long GetFileSize(string url)
    {
        HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
        httpWebRequest.KeepAlive = false;
        httpWebRequest.Timeout = 2000;
        httpWebRequest.Method = "HEAD";
        HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
        return httpWebResponse.ContentLength;
    }
}
